package org.beetl.support;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 默认的命名映射. 数据库命名规则: 1.列名全部大写.例如:USERNAME.
 * 2.多个单词用下划线分开.例如:USER_NAME,USER_PASSWORD. 属性列名:username USERNAME 列名属性:USERNAME
 * username 属性列名:Username USERNAME 属性列名:userName USER_NAME 属性列名:UserName
 * USER_NAME 列名属性:USER_NAME userName
 * </p>
 * 
 * @author zhoupan.
 */
public class DefaultNameMapper implements NameMapper {

 /**
  * 根据Java命名约定判断指定的名称是否为属性名. 1.首字母小写 2.首个单词小写.(多个单词不用_连接)
  * 
  * @param name
  * @return
  */
 public boolean isPropertyName(String name) {
  if (CommonSupport.contains(name, NameMapper.UNDERCORE)) {
   return false;
  }
  return CommonSupport.equals(CommonSupport.uncapitalize(name), name);
 }

 /*
  * (non-Javadoc)
  * 
  * @see
  * com.whcyit.framework.ormlite.INameMapper#getPropertyName(java.lang.String)
  */
 
 public String getPropertyName(String columnName) {
  if (CommonSupport.isBlank(columnName)) {
   return "";
  }
  if (this.isPropertyName(columnName)) {
   return columnName;
  }
  String[] parts = CommonSupport.split(columnName.toUpperCase(), NameMapper.UNDERCORE);
  if (parts != null && parts.length > 0) {
   List<String> properties = new ArrayList<String>();
   for (String part : parts) {
    if (CommonSupport.isNotBlank(part)) {
     if (properties.isEmpty()) {
      properties.add(part.toLowerCase());
     } else {
      properties.add(CommonSupport.capitalize(part.toLowerCase()));
     }
    }
   }
   if (!properties.isEmpty()) {
    return CommonSupport.join(properties.iterator(), "");
   }
  }
  return "";
 }

 /*
  * (non-Javadoc)
  * 
  * @see
  * com.whcyit.framework.ormlite.INameMapper#getColumnName(java.lang.String)
  */
 
 public String getColumnName(String propertyName) {
  if (CommonSupport.isBlank(propertyName)) {
   return "";
  }
  List<String> words = new ArrayList<String>();
  int wordIndex = 0;
  for (int i = 1; i < propertyName.length() - 1; i++) {
   String thisOne = CommonSupport.substring(propertyName, i, i + 1);
   if (CommonSupport.equals(thisOne.toUpperCase(), thisOne)) {
    words.add(CommonSupport.substring(propertyName, wordIndex, i).toUpperCase());
    wordIndex = i;
   }
  }
  words.add(CommonSupport.substring(propertyName, wordIndex).toUpperCase());
  return CommonSupport.join(words.iterator(), NameMapper.UNDERCORE);
 }
}
